package com.garlicts.framework.core;

import com.garlicts.framework.ioc.IocInit;
import org.slf4j.Logger;

import com.garlicts.framework.aop.AopProxyComponent;
import com.garlicts.framework.ioc.BeanContainerComponent;
import com.garlicts.framework.util.ClassUtil;

import org.slf4j.LoggerFactory;

import java.lang.reflect.Method;
import java.util.List;

/**
 * 组件加载器
 *
 * @author 水木星辰
 * @since 1.0
 */
public final class ComponentLoader {
	
	private static Logger logger = LoggerFactory.getLogger(ComponentLoader.class);

    public static void init() {
        // 定义需要加载的 Helper 类
        Class<?>[] componentList = {
            BeanContainerComponent.class,
            AopProxyComponent.class
        };
        // 按照顺序加载类
        for (Class<?> cls : componentList) {
            ClassUtil.loadClass(cls.getName());
            logger.info(new StringBuffer("加载框架组件：").append(cls.getName()).toString());
        }

        invokeIocInit();

        ClassUtil.loadClass("com.garlicts.framework.extension.PluginComponent");

        invokeInitData();

    }

//    private void invokePlugin() {
//        List<Plugin> pluginList = PluginComponent.getPluginList();
//        for (Plugin plugin : pluginList) {
//            plugin.init();
//        }
//    }
//
//    private void destroyPlugin() {
//        List<Plugin> pluginList = PluginComponent.getPluginList();
//        for (Plugin plugin : pluginList) {
//            plugin.destroy();
//        }
//    }

    private static void invokeInitData(){
        BeanLoader beanLoader = InstanceFactory.getBeanLoader();
        List<Class<?>> initDataClassList = beanLoader.getBeanClassListBySuper(Initialization.class);
        for(Class<?> cls : initDataClassList){
            try {
                Object initInstatnce = BeanContainerComponent.getBean(cls);
                Method initMethod = cls.getDeclaredMethod("init", new Class[]{});
                initMethod.setAccessible(true);
                initMethod.invoke(initInstatnce, new Object[]{});
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private static void invokeIocInit(){
        BeanLoader beanLoader = InstanceFactory.getBeanLoader();
        List<Class<?>> iocInitClassList = beanLoader.getBeanClassListBySuper(IocInit.class);
        for(Class<?> cls : iocInitClassList){
            try {
                Object o = BeanContainerComponent.getBean(cls);
                Method initMethod = cls.getDeclaredMethod("init", new Class[]{});
                initMethod.setAccessible(true);
                initMethod.invoke(o, new Object[]{});
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}
